<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>
	<button>GET</button>
	<button>POST</button>
	<button>DELETE</button>
	<button>PUT</button>
	<button>PATCH</button>
</body>
<script>
	// 1- 请求方式  2- 请求地址 3- 发送参数   4- 得到的响应（响应体）
	// 请求体（POST,PUT,PATCH)
	const btns = document.querySelectorAll("button");
	// get
	btns[0].onclick = function(){
		// 生成xhr实例
		const xhr = new XMLHttpRequest();
		xhr.responseType = "json";// 指定数据格式为JSON
		// 指定请求方式，请求地址
		xhr.open("get","http://zhangpeiyue.com/scoreList?age=12&sex=男");
		xhr.send();
		// 当得到响应体后执行
		xhr.onload = function(){
			console.log(xhr.response);
		}
	}
	// post
	btns[1].onclick = function(){
		// application/json
		// const xhr = new XMLHttpRequest();
		// xhr.open("post","http://zhangpeiyue.com/scoreList");
		// xhr.setRequestHeader("Content-Type","application/json")
		// xhr.send(JSON.stringify({
		// 	userName:"刘德华",
		// 	age:60
		// }));
		// xhr.onload = function(){
		// 	console.log(xhr.response);// 响应体
		// }
		
		// application/x-www-form-urlencoded"
		const xhr = new XMLHttpRequest();
		xhr.open("post","http://zhangpeiyue.com/scoreList");
		xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
		xhr.send("userName=黎明&age=65");
		xhr.onload = function(){
			console.log(xhr.response);// 响应体
		}
	}
	// put
	btns[3].onclick = function(){
		const xhr = new XMLHttpRequest();
		xhr.open("put","http://zhangpeiyue.com/scoreList/1");
		xhr.setRequestHeader("Content-Type","application/json");
		xhr.send(JSON.stringify({
			userName:"郭富城",
			age:100
		}));
	}
	// patch
	btns[4].onclick = function(){
		const xhr = new XMLHttpRequest();
		xhr.responseType = "json";
		xhr.open("PATCH","http://zhangpeiyue.com/scoreList/2");
		xhr.setRequestHeader("Content-Type","application/json");
		xhr.send(JSON.stringify({
			userName:"张学友",
			age:20
		}))
		xhr.onload = function(){
			console.log(xhr.response);
		}
	}
	// delete
	btns[2].onclick = function(){
		const xhr = new XMLHttpRequest();
		xhr.responseType = "json";
		xhr.open("delete","http://zhangpeiyue.com/scoreList/3");
		xhr.send()
		xhr.onload = function(){
			console.log(xhr.response);
		}
	}
</script>
</html>